Unit-1,2,3 QB Solution

Manish Patel

Nov 10, 2023

UNIT-1

1. Program to add two numbers with user input:

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
sum = num1 + num2
print("The sum is:", sum)
Enter first number: 2
Enter second number: 3
The sum is: 5.0

2. Program to find the area of a circle:

pi = 3.14
radius = float(input("Enter the radius of the circle: "))
area = pi * radius**2
print("The area of the circle is:", area)
Enter the radius of the circle: 7
The area of the circle is: 153.86

3. Program to find the area of a triangle:

base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
area = 0.5 * base * height
print("The area of the triangle is:", area)
Enter the base of the triangle: 5
Enter the height of the triangle: 10
The area of the triangle is: 25.0

4. Program to calculate the area of a trapezoid:

base1 = float(input("Enter the length of the first base: "))
base2 = float(input("Enter the length of the second base: "))
height = float(input("Enter the height of the trapezoid: "))
area = 0.5 * (base1 + base2) * height
print("The area of the trapezoid is:", area)
Enter the length of the first base: 10
Enter the length of the second base: 20
Enter the height of the trapezoid: 30
The area of the trapezoid is: 450.0

5. Program to calculate the surface volume and area of a cylinder:

pi = 3.14

radius = float(input("Enter the radius of the cylinder: "))
height = float(input("Enter the height of the cylinder: "))

volume = pi * radius**2 * height
area = 2 * pi * radius * (radius + height)

print("The volume of the cylinder is:", volume)
print("The surface area of the cylinder is:", area)
Enter the radius of the cylinder: 5
Enter the height of the cylinder: 10
The volume of the cylinder is: 785.0
The surface area of the cylinder is: 471.00000000000006

6. Program to convert Fahrenheit to Celsius and vice versa:

#input celsius
celsius = float(input("Enter Celsius: "))

#calculate fahrenheit using the formula
fahrenheit = (9/5)*celsius + 32
print("Fahrenheit ",fahrenheit)

#input fahrenheit
fahrenheit = float(input("Enter Fahrenheit: "))

celsius = (5/9)*(fahrenheit - 32)
print("Celsius ",celsius)
Enter Celsius: 37
Fahrenheit  98.60000000000001
Enter Fahrenheit: 98
Celsius  36.66666666666667

7. Calculator functionality demonstration:

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y != 0:
        return x / y
    else:
        return "Cannot divide by zero."

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operator = input("Enter operator (+, -, *, /): ")

if operator == '+':
    result = add(num1, num2)
elif operator == '-':
    result = subtract(num1, num2)
elif operator == '*':
    result = multiply(num1, num2)
elif operator == '/':
    result = divide(num1, num2)
else:
    result = "Invalid operator."

print(f"The result is: {result}")
Enter first number: 4
Enter second number: 5
Enter operator (+, -, *, /): *
The result is: 20.0

8. Program to convert days into years, months, and days:

days = int(input("Enter the number of days: "))

years = days // 365
months = (days % 365) // 30
remaining_days = (days % 365) % 30

print(f"Years: {years}, Months: {months}, Days: {remaining_days}")
Enter the number of days: 398
Years: 1, Months: 1, Days: 3

9. Program to convert hours into minutes and seconds:

hours = int(input("Enter the number of hours: "))

minutes = hours * 60
seconds = hours * 3600

print(f"Minutes: {minutes}, Seconds: {seconds}")
Enter the number of hours: 6
Minutes: 360, Seconds: 21600

10. Program to find an integer exponent x such that a^x = n:

def find_exponent(a, n):
    x = 0
    while a ** x != n:
        x += 1
    return x

a1, n1 = 2, 1024
a2, n2 = 3, 81

print(f"For a = {a1} and n = {n1}, the exponent x is: {find_exponent(a1, n1)}")
print(f"For a = {a2} and n = {n2}, the exponent x is: {find_exponent(a2, n2)}")
For a = 2 and n = 1024, the exponent x is: 10
For a = 3 and n = 81, the exponent x is: 4

UNIT-2

1. Determine if a given number is odd or even:

number = int(input("Enter a number "))

if number % 2 == 0:
    print("Number is Even")
else:
    print("Number is ODD")
Enter a number 5
Number is ODD

2. Check if the input number is positive, negative, or zero:

number = int(input("Enter a number : "))

if number > 0:
    print("Positive")
elif number < 0:
    print("Negative")
else:
    print("Zero")
Enter a number : -7
Negative

3. Find the maximum number among three input numbers:

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
c = int(input("Enter the third number: "))

# Find the maximum of two numbers
max_number = a
if b > max_number:
    max_number = b

# If the third number is greater than the maximum of two numbers, then it is the maximum number
if c > max_number:
    max_number = c

# Print the maximum number
print("Maximum number is:", max_number)
Enter the first number: 4
Enter the second number: 5
Enter the third number: 6
Maximum number is: 6

4. Check if a year is a leap year or not:

year = int(input("Enter a year : "))

if year % 4 == 0:
    if year % 100 != 0 or year % 400 == 0:
        print("Leap Year")
    else:
        print("Not a Leap Year")
else:
    print("Not a Leap Year")
Enter a year : 2000
Leap Year

5. Find the sum of the first N natural numbers:

N = int(input("Enter the value of N : "))

sum_natural = (N * (N + 1)) // 2
print("Sum of first", N, "natural numbers is:", sum_natural)
Enter the value of N : 10
Sum of first 10 natural numbers is: 55

6. Find the average of the first N natural numbers:

N = int(input("Enter the value of N : "))

average = (N * (N + 1)) / (2 * N)
print("Average of first", N, "natural numbers is:", average)
Enter the value of N : 10
Average of first 10 natural numbers is: 5.5

7. Check how many numbers between ‘a’ and ‘b’ are divisible by ‘c’:

a = int(input("Enter the value of a: "))
b = int(input("Enter the value of b: "))
c = int(input("Enter the value of c: "))
count = 0

for number in range(a, b + 1):
    if number % c == 0:
        count += 1

print("Number of numbers divisible by", c, "between", a, "and", b, "is:", count)
Enter the value of a: 1
Enter the value of b: 10
Enter the value of c: 3
Number of numbers divisible by 3 between 1 and 10 is: 3

9. Multiplication table of a given number:

num = int(input("Enter a number: "))
for i in range(1, 11):
    print(f"{num} x {i} = {num * i}")
Enter a number: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

10. Factorial of a number:

num = int(input("Enter a number: "))
factorial = 1
for i in range(1, num + 1):
    factorial *= i
print(f"The factorial of {num} is {factorial}")
Enter a number: 5
The factorial of 5 is 120

11. Fibonacci sequence up to n-th term:

n = int(input("Enter the number of terms: "))
a, b = 0, 1
for _ in range(n):
    print(a, end=" ")
    a, b = b, a + b
Enter the number of terms: 10
0 1 1 2 3 5 8 13 21 34 

12. Average of 10 values entered by the user:

total = 0
for _ in range(10):
    num = float(input("Enter a number: "))
    total += num
average = total / 10
print(f"The average is: {average}")
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
Enter a number: 6
Enter a number: 7
Enter a number: 8
Enter a number: 9
Enter a number: 10
The average is: 5.5

13. Reverse a number:

num = int(input("Enter a number: "))
reverse_num = 0
while num > 0:
    reverse_num = reverse_num * 10 + num % 10
    num = num // 10
print(f"The reversed number is: {reverse_num}")
Enter a number: 123
The reversed number is: 321

14. Check if a number is Armstrong number:

num = int(input("Enter a number: "))
temp = num
sum = 0
while temp > 0:
    digit = temp % 10
    sum += digit ** 3
    temp //= 10
if num == sum:
    print(f"{num} is an Armstrong number")
else:
    print(f"{num} is not an Armstrong number")
Enter a number: 153
153 is an Armstrong number

15. Check if a number is prime:

num = int(input("Enter a number: "))
is_prime = True
for i in range(2, int(num**0.5) + 1):
    if num % i == 0:
        is_prime = False
        break
if is_prime and num > 1:
    print(f"{num} is a prime number")
else:
    print(f"{num} is not a prime number")
Enter a number: 41
41 is a prime number

Pattern 1:

for i in range(1, 5):
    print('* ' * i)
* 
* * 
* * * 
* * * * 

Pattern 2:

rows = 4
i = rows
while i >= 1:
    j = rows
    while j > i:
        # display space
        print(' ', end=' ')
        j -= 1
    k = 1
    while k <= i:
        print('*', end=' ')
        k += 1
    print()
    i -= 1
* * * * 
  * * * 
    * * 
      * 

Pattern 3:

print("Print equilateral triangle Pyramid using asterisk symbol ")
# printing full Triangle pyramid using stars
size = 5
m = (2 * size) - 2
for i in range(0, size):
    for j in range(0, m):
        print(end=" ")
    # decrementing m after each loop
    m = m - 1
    for j in range(0, i + 1):
        print("*", end=' ')
    print(" ")
Print equilateral triangle Pyramid using asterisk symbol 
        *  
       * *  
      * * *  
     * * * *  
    * * * * *  

Pattern 4:

for i in range(4, 0, -1):
    print('* ' * i)
* * * * 
* * * 
* * 
* 

Pattern 5:

for i in range(5):
    for j in range(1, 6 - i):
        print(j, end=' ')
    print()
1 2 3 4 5 
1 2 3 4 
1 2 3 
1 2 
1 

Pattern 6:

for i in range(4):
    for j in range(1, i + 2):
        print(j, end=' ')
    print()
1 
1 2 
1 2 3 
1 2 3 4 

Pattern 7:

for i in range(4):
    for _ in range(i + 1):
        print(i + 1, end=' ')
    print()
1 
2 2 
3 3 3 
4 4 4 4 

Pattern 8:

for i in range(4):
    for _ in range(i + 1):
        print('*', end=' ')
    print()
    for _ in range(i + 1):
        print('#', end=' ')
    print()
* 
# 
* * 
# # 
* * * 
# # # 
* * * * 
# # # # 

Pattern 9:

for i in range(4):
    for j in range(i + 1):
        print((i + j) % 2, end=' ')
    print()
0 
1 0 
0 1 0 
1 0 1 0 

Pattern 10:

for i in range(4):
    for j in range(i + 1):
        print((i + j) % 2, end=' ')
    print()
0 
1 0 
0 1 0 
1 0 1 0 

Pattern 11:

for i in range(4):
    for j in range(i + 1):
        print(j + 1, end=' ')
    print()
1 
1 2 
1 2 3 
1 2 3 4 

Pattern 12:

for i in range(4):
    for _ in range(i + 1):
        print(i + 1, end=' ')
    print()
1 
2 2 
3 3 3 
4 4 4 4 

Write a Python Program to make the gross pay, annual income and income tax calculator using following data.

The gross pay consists of Basic Pay, House Rent Allowance (hra), Dearness Allowance (dra), other allowances and professional tax and provident fund. Gross Pay= Basic Pay+ House Rent Allowance (hra) + Dearness Allowance (dra) +other allowances +Transport Allowance (TA)– Professional tax –Employees’ Provident fund (EPF) Basic Pay for different grade levels are indicated in table given. The Professional tax remains constant and that is equal to 200 Rs. for each grade levels and each month. House Rent Allowance (hra) varies as per the city- For Class 1 Cities it is 0.3 times of Basic Pay of each grade levels, for Class 2 Cities it is 0.2 times of Basic Pay of each grade levels, for Class 3 Cities it is 0.1 times of Basic Pay of each grade levels, Dearness Allowance (dra)= 0.5 times of Basic Pay of each grade levels, Other allowances are given in table which varies according to different grade levels, Provident Fund= 0.11 times of Basic Pay for each grade levels, Transport Allowance remains constant as 900 Rs. for each levels.

For different grade pays:

Grade Levels Basic Pay (in Rs.) Other Allowances (in Rs.)
A (Considered as highest grade pay) 60000 8000
B 50000 7000
C 40000 6000
D 30000 5000
E 20000 4000
F 10000 3000

The gross pay calculated is only for one month. After calculating Gross Pay of each employee calculate the annual pay for employee by multiplying gross pay calculated, by 12. So, Annual Pay of an employee=Gross Pay of an employee*12

From Annual Pay of an Employee Calculate the income tax as per the slabs of India Income Tax 2022-23 given below. Tax Slabs for AY 2022-23

Income Tax Rate

Amount in Rs. Income Tax Rate
“Up to Rs. 2,50,000” 0%
“Rs. 2,50,001 to Rs.5,00,000” “5% above Rs. 2,50,000”
“Rs. 5,00,001 to Rs. 7,50,000” “10% above Rs. 5,00,000 + Rs. 12,500”
“Rs. 7,50,001 to Rs. 10,00,000” “15% above Rs. 7,50,000 + Rs. 37,500”
“Rs. 10,00,001 to Rs. 12,50,000” “20% above Rs. 10,00,000 + Rs. 75,000”
“Rs. 12,50,001 to Rs. 15,00,000” “25% above Rs. 12,50,000 + Rs. 1,25,000”
“Above Rs. 15,00,001” “30% above Rs. 15,00,000 + Rs. 1,87,500”

Test Input & Output:
- Enter the grade_level (A,B,C,D,E or F:) A
- city 1 is a tier 1 (metro), city 2 is tier 2 and city 3 is tier 3 - Enter the city (1,2 or 3) 1
- Gross Pay of an Employee is: 110100.0
- Annual income of an employee is: 1321200.0
- Income Tax to be paid by an employee is: 142800.0

# Function to calculate Gross Pay
def calculate_gross_pay(grade_level, city):
    if grade_level == 'A':
        basic_pay = 60000
        other_allowances = 8000
    elif grade_level == 'B':
        basic_pay = 50000
        other_allowances = 7000
    elif grade_level == 'C':
        basic_pay = 40000
        other_allowances = 6000
    elif grade_level == 'D':
        basic_pay = 30000
        other_allowances = 5000
    elif grade_level == 'E':
        basic_pay = 20000
        other_allowances = 4000
    elif grade_level == 'F':
        basic_pay = 10000
        other_allowances = 3000
    else:
        print("Invalid grade level entered.")
        return None

    hra = calculate_hra(grade_level, city)
    dra = 0.5 * basic_pay
    transport_allowance = 900
    professional_tax = 200
    epf = 0.11 * basic_pay

    gross_pay = basic_pay + hra + dra + other_allowances + transport_allowance - professional_tax - epf
    return gross_pay

# Function to calculate HRA based on city
def calculate_hra(grade_level, city):
    basic_pay = 0
    if grade_level == 'A':
        basic_pay = 60000
    elif grade_level == 'B':
        basic_pay = 50000
    elif grade_level == 'C':
        basic_pay = 40000
    elif grade_level == 'D':
        basic_pay = 30000
    elif grade_level == 'E':
        basic_pay = 20000
    elif grade_level == 'F':
        basic_pay = 10000

    if city == 1:
        return 0.3 * basic_pay
    elif city == 2:
        return 0.2 * basic_pay
    elif city == 3:
        return 0.1 * basic_pay
    else:
        print("Invalid city entered.")
        return None

# Function to calculate Income Tax
def calculate_income_tax(annual_income):
    if annual_income <= 250000:
        return 0
    elif 250001 <= annual_income <= 500000:
        return 0.05 * (annual_income - 250000)
    elif 500001 <= annual_income <= 750000:
        return 0.10 * (annual_income - 500000) + 12500
    elif 750001 <= annual_income <= 1000000:
        return 0.15 * (annual_income - 750000) + 37500
    elif 1000001 <= annual_income <= 1250000:
        return 0.20 * (annual_income - 1000000) + 75000
    elif 1250001 <= annual_income <= 1500000:
        return 0.25 * (annual_income - 1250000) + 125000
    else:
        return 0.30 * (annual_income - 1500000) + 187500

# Input from user
grade_level = input("Enter the grade level (A, B, C, D, E, or F): ").upper()
city = int(input("Enter the city (1, 2, or 3): "))

# Calculate Gross Pay, Annual Income, and Income Tax
gross_pay = calculate_gross_pay(grade_level, city)

if gross_pay != None:
    annual_income = gross_pay * 12
    income_tax = calculate_income_tax(annual_income)

    # Display results
    print(f"Gross Pay of an Employee is: {gross_pay}")
    print(f"Annual income of an employee is: {annual_income}")
    print(f"Income Tax to be paid by an employee is: {income_tax}")
Enter the grade level (A, B, C, D, E, or F): A
Enter the city (1, 2, or 3): 1
Gross Pay of an Employee is: 110100.0
Annual income of an employee is: 1321200.0
Income Tax to be paid by an employee is: 142800.0

DISARIUM AND HARSHAD NUMBERS

def digit_count(number):
    count = 0
    while number > 0:
        number //= 10
        count += 1
    return count

def is_disarium(number):
    temp = number
    count = digit_count(temp)
    sum_disarium = 0
    while temp > 0:
        digit = temp % 10
        sum_disarium += digit ** count
        temp //= 10
        count -= 1
    return sum_disarium == number

def is_harshad(number):
    temp = number
    sum_digits = 0
    while temp > 0:
        sum_digits += temp % 10
        temp //= 10
    return number % sum_digits == 0

for i in range(1, 101):
    if is_disarium(i) and is_harshad(i):
        print(i)
1
2
3
4
5
6
7
8
9

Ask the user to enter 10 test scores. Write a program to do the following:

  • Print out the highest and lowest scores.
  • Print out the average of the scores.
  • Print out the second largest score.
  • If any of the scores is greater than 100, then after all the scores have been entered, print a message warning the user that a value over 100 has been entered.
  • Drop the two lowest scores and print out the average of the rest of them.

def analyze_scores():
    highest = None
    second_largest = None
    lowest = None
    second_lowest = None
    total = 0
    count = 0
    has_warning = False

    for i in range(10):
        score = float(input(f"Enter test score {i + 1}: "))

        if score > 100:
            has_warning = True

        # Initialize values on the first iteration
        if count == 0:
            highest = score
            lowest = score
        else:
            # Find highest score
            if score > highest:
                second_largest = highest
                highest = score
            elif second_largest == None or score > second_largest:
                second_largest = score

            # Find lowest score
            if score < lowest:
                second_lowest = lowest
                lowest = score
            elif second_lowest == None or score < second_lowest:
                second_lowest = score

        # Find average
        total += score
        count += 1

    average = total / count

    # Display results
    print("Highest Score:", highest)
    print("Second Largest Score:", second_largest if count > 1 \
          else "There is no second largest score.")
    print("Lowest Score:", lowest)
    print("Average Score:", average)

    if has_warning:
        print("Warning: A score over 100 has been entered.")

    # Calculate average after dropping two lowest scores
    if count > 2:
        total_after_dropping = total - lowest - second_lowest
        count_after_dropping = count - 2
        average_after_dropping = total_after_dropping / count_after_dropping
        print("Average after dropping two lowest scores:", average_after_dropping)
    else:
        print("There are not enough scores to calculate \
        the average after dropping two lowest scores.")


# Call the function to analyze the scores
analyze_scores()
Enter test score 1: 1
Enter test score 2: 2
Enter test score 3: 3
Enter test score 4: 4
Enter test score 5: 5
Enter test score 6: 6
Enter test score 7: 7
Enter test score 8: 8
Enter test score 9: 9
Enter test score 10: 10
Highest Score: 10.0
Second Largest Score: 9.0
Lowest Score: 1.0
Average Score: 5.5
Average after dropping two lowest scores: 6.5

Write a program to encode a number by changing the digits in the given positive integer by user. The rule for changing the digits in number will be:If the digit in number is between 0 to 8 than replace the number with 1 to 9 respectively. (incrementing each digit by +1).If the digit is 9, then replace it with 0.To encode a number, replace digits in following manner:For example:Input: 31590218 Output: The number after encoding is: 42601329

def encode_number(number):
    encoded_number = 0
    multiplier = 1
    
    while number > 0:
        digit = number % 10
        if digit == 9:
            encoded_number += 0 * multiplier
        else:
            encoded_number += (digit + 1) * multiplier
        multiplier *= 10
        number //= 10
    
    return encoded_number

# Get input from the user
user_input = int(input("Enter a positive integer: "))

# Encode the number
encoded_result = encode_number(user_input)

# Display the result
print("The number after encoding is:", encoded_result)
Enter a positive integer: 31590218
The number after encoding is: 42601329

Write a python program to swap first and last digits of a number using loop.(for example: input = 123456 then output=623451)

def swap_first_and_last_digits(number):
    # Find the number of digits in the number
    num_digits = 0
    temp = number
    while temp > 0:
        temp //= 10
        num_digits += 1

    # Handle the case where the number has only one digit
    if num_digits <= 1:
        return number

    # Extract the first and last digits
    first_digit = number // (10 ** (num_digits - 1))
    last_digit = number % 10

    # Remove the first and last digits
    number_without_first_last = (number % (10 ** (num_digits - 1))) // 10

    # Swap and reconstruct the number
    swapped_number = last_digit * (10 ** (num_digits - 1)) + number_without_first_last * 10 + first_digit

    return swapped_number

# Get input from the user
user_input = int(input("Enter a number: "))

# Swap the first and last digits
result = swap_first_and_last_digits(user_input)

# Display the result
print("After swapping the first and last digits:", result)
Enter a number: 123456
After swapping the first and last digits: 623451

PATTERN PROGRAM

n = 0

while n <= 0 or n % 2 == 0:
    n = int(input("Enter an odd number as the number of lines: "))

for i in range(1, n + 1):
    for j in range(1, n + 1):
        if (i <= n // 2 and j > i and j <= n - i) or (i > n // 2 and j < i and j > n - i + 1):
            print(" ", end="")
        else:
            print("*", end="")
    print()
Enter an odd number as the number of lines: 9
*       *
**     **
***   ***
**** ****
*********
**** ****
***   ***
**     **
*       *

Write a program to implement the calculator for the date of Easter.

The following algorithm computes the date for Easter Sunday for any year between 1900 to 2099. Ask the user to enter a year. Compute the following: 1. a = year % 19 2. b = year % 4 3. c = year % 7 4. d = (19 * a + 24) % 30 5. e = (2 * b + 4 * c + 6 * d + 5) % 7 6. dateofeaster = 22 + d + e Special note: The algorithm can give a date in April. You will know that the date is in April if the calculation gives you an answer greater than 31. (You’ll need to adjust) Also, if the year is one of four special years (1954, 1981, 2049, or 2076) then subtract 7 from the date. Eg: Input: Year : 2022 Expected Outcome: 2022-04-17 (i.e. 17th April 2022)

def calculate_easter_date(year):
    a = year % 19
    b = year % 4
    c = year % 7
    d = (19 * a + 24) % 30
    e = (2 * b + 4 * c + 6 * d + 5) % 7

    date_of_easter = 22 + d + e

    # Adjust if the date is in April
    if date_of_easter > 31:
        date_of_easter -= 31

    # Special adjustment for certain years
    if year in [1954, 1981, 2049, 2076]:
        date_of_easter -= 7

    return f"{year}-04-{date_of_easter:02d}"

# Get input from the user
user_input = int(input("Enter a year (1900-2099): "))

# Validate input year
if 1900 <= user_input <= 2099:
    result = calculate_easter_date(user_input)
    print(f"The date of Easter Sunday in {user_input} is: {result}")
else:
    print("Please enter a year between 1900 and 2099.")
Enter a year (1900-2099): 2022
The date of Easter Sunday in 2022 is: 2022-04-17

GCD PROGRAM

def calculate_gcd(a, b):
    while b:
        a, b = b, a % b
    return a

# Get input from the user
num1 = int(input("Enter the first positive integer: "))
num2 = int(input("Enter the second positive integer: "))

# Validate input
if num1 > 0 and num2 > 0:
    # Calculate GCD
    gcd_result = calculate_gcd(num1, num2)
    print(f"The GCD of {num1} and {num2} is: {gcd_result}")
else:
    print("Please enter positive integers.")
Enter the first positive integer: 8
Enter the second positive integer: 24
The GCD of 8 and 24 is: 8

Write a python program that prompts the user to enter numbers and stops only when the use enter “QUIT” . After this print sum and average of the numbers, minimum and maximum number from given numbers entered by user.

Note: you are not allowed to use any built in structures like, list ,tuple etc. or any builtin function like min, max etc. For Example: Input: 4,1,5,”QUIT” Output: Sum=10 Average=3.333 Minimum number=1 Maximum number=5

# Initialize variables
sum = 0
count = 0
minimum = None
maximum = None

# Prompt the user to enter numbers
while True:
    number = input("Enter a number: ")

    # If the user enters "QUIT", stop the loop
    if number == "QUIT":
        break

    # Convert the number to an integer
    number = int(number)

    # Update the sum and count variables
    sum += number
    count += 1

    # Update the minimum and maximum variables
    if minimum == None or number < minimum:
        minimum = number
    if maximum == None or number > maximum:
        maximum = number

# Calculate the average
average = sum / count

# Print the results
print("Sum:", sum)
print("Average:", average)
print("Minimum:", minimum)
print("Maximum:", maximum)
Enter a number: 4
Enter a number: 1
Enter a number: 5
Enter a number: QUIT
Sum: 10
Average: 3.3333333333333335
Minimum: 1
Maximum: 5

HOTEL BOOKING PROBLEM

Booking Chart

def calculate_studio_rent(month, nights):
    studio_night_rate = 0

    if month == "January" or month == "February" or month == "March" or month == "April":
        studio_night_rate = 50
        if nights > 7:
            studio_night_rate *= 0.7
        elif nights > 3:
            studio_night_rate *= 0.8
    elif month == "May" or month == "June" or month == "July" or month == "August":
        studio_night_rate = 70
        if nights > 7:
            studio_night_rate *= 0.8
        elif nights > 3:
            studio_night_rate *= 0.9
    elif month == "September" or month == "October" or month == "November" or month == "December":
        studio_night_rate = 80
        if nights > 7:
            studio_night_rate *= 0.9
        elif nights > 3:
            studio_night_rate *= 0.95

    return studio_night_rate * nights

def calculate_apartment_rent(nights):
    apartment_night_rate = 0

    if month == "January" or month == "February" or month == "March" or month == "April":
        apartment_night_rate = 60
        if nights > 7:
            studio_night_rate *= 0.9
      
    elif month == "May" or month == "June" or month == "July" or month == "August":
        apartment_night_rate = 80
        if nights > 7:
            studio_night_rate *= 0.8
        
    elif month == "September" or month == "October" or month == "November" or month == "December":
        apartment_night_rate = 90
        if nights > 7:
            studio_night_rate *= 0.9
    

    return apartment_night_rate * nights

# Input from user
month = input("Enter the month of stay: ")
nights = int(input("Enter the number of nights: "))

# Calculate rents
studio_rent = calculate_studio_rent(month, nights)
apartment_rent = calculate_apartment_rent(nights)

# Display results
print(f"Studio Rent for {nights} nights is ${studio_rent}")
print(f"Apartment Rent for {nights} nights is ${apartment_rent}")
Enter the month of stay: May
Enter the number of nights: 5
Studio Rent for 5 nights is $315.0
Apartment Rent for 5 nights is $400

Write a program that enters a single digit integer number and produces all possible 6-digit numbers for which the product of their digits is equal to the entered number.

def find_numbers(product):
    for a in range(1, 10):
        for b in range(0, 10):
            for c in range(0, 10):
                for d in range(0, 10):
                    for e in range(0, 10):
                        for f in range(0, 10):
                            if a * b * c * d * e * f == product:
                                print(a * 100000 + b * 10000 + c * 1000 + d * 100 + e * 10 + f)

# Get user input
entered_number = int(input("Enter a single digit integer number: "))

if 0 <= entered_number <= 9:
    print(f"All possible 6-digit numbers for which the product of their digits is {entered_number}:")
    find_numbers(entered_number)
else:
    print("Please enter a single digit integer.")
Enter a single digit integer number: 2
All possible 6-digit numbers for which the product of their digits is 2:
111112
111121
111211
112111
121111
211111

Write a Python program that prompts the user to enter numbers and stops only when the user enters “stop”. After this, print the minimum even, maximum even, average of even number, minimum odd, maximum odd, average of odd number from among all the numbers entered by the user.

Note: You are not allowed to use any built-in structures like lists, tuples, etc. or any built-in functions like max, min, sum Example: input and output enter number or q for’stop:‘-1 enter number or q for’stop:’-5 enter number or q for’stop:’9 enter number or q for’stop:’2 enter number or q for’stop:’4 enter number or q for’stop:’6 enter number or q for’stop:’stop Output: for even 6 2 4.0 (max, min, avg) for odd 9 -5 1.0 (max, min, avg)

# Initialize variables
minimum_even = None
maximum_even = None
sum_even = 0
count_even = 0
minimum_odd = None
maximum_odd = None
sum_odd = 0
count_odd = 0

# Prompt the user to enter numbers
while True:
    number = input("Enter a number or 'stop': ")

    # If the user enters "stop", stop the loop
    if number == "stop":
        break

    # Convert the number to an integer
    number = int(number)

    # If the number is even
    if number % 2 == 0:
        # Update the minimum and maximum even variables
        if minimum_even == None or number < minimum_even:
            minimum_even = number
        if maximum_even == None or number > maximum_even:
            maximum_even = number

        # Update the sum and count even variables
        sum_even += number
        count_even += 1

    # If the number is odd
    else:
        # Update the minimum and maximum odd variables
        if minimum_odd == None or number < minimum_odd:
            minimum_odd = number
        if maximum_odd == None or number > maximum_odd:
            maximum_odd = number

        # Update the sum and count odd variables
        sum_odd += number
        count_odd += 1

# Calculate the average of even and odd numbers
average_even = sum_even / count_even if count_even > 0 else None
average_odd = sum_odd / count_odd if count_odd > 0 else None

# Print the results
print("Results for even numbers:")
print("Minimum:", minimum_even)
print("Maximum:", maximum_even)
print("Average:", average_even)

print("Results for odd numbers:")
print("Minimum:", minimum_odd)
print("Maximum:", maximum_odd)
print("Average:", average_odd)
Enter a number or 'stop': 1
Enter a number or 'stop': 2
Enter a number or 'stop': 3
Enter a number or 'stop': 4
Enter a number or 'stop': 5
Enter a number or 'stop': 6
Enter a number or 'stop': 7
Enter a number or 'stop': 8
Enter a number or 'stop': 9
Enter a number or 'stop': 10
Enter a number or 'stop': stop
Results for even numbers:
Minimum: 2
Maximum: 10
Average: 6.0
Results for odd numbers:
Minimum: 1
Maximum: 9
Average: 5.0

Write your own python program for computing square roots that implements Newton’s Method. Use of inbuilt function, math library or x**0.5 is not allowed.

Newton Method is a category of guess-and-check approach. You first guess what the square root might be and then see how close your guess is. You can use this information to make another guess and continue guessing until you have found the square root (or a close approximation to it). Suppose x is the number we want the root of and guess is the current guessed answer. The guess can be improved by using (guess+ x/guess)/2 as the next guess.

The program should -

  1. Prompt the user for the value to find the square root of (x) and the number of times to improve the guess.
  2. Starting with a guess value of x/2, your program should loop the specified number of times applying Newton’s method and report the final value of guess.

def newton_sqrt(x, num_iterations):
    guess = x / 2  # Initial guess

    for _ in range(num_iterations):
        guess = (guess + x / guess) / 2

    return guess

# Prompt user for input
x = float(input("Enter a number to find the square root of: "))
num_iterations = int(input("Enter the number of iterations for Newton's Method: "))

# Check for valid input
if x < 0 or num_iterations <= 0:
    print("Please enter a positive number and a positive number of iterations.")
else:
    # Compute square root using Newton's Method
    result = newton_sqrt(x, num_iterations)
    print(f"The square root of {x} using Newton's Method after {num_iterations} iterations is approximately: {result:.6f}")
Enter a number to find the square root of: 25
Enter the number of iterations for Newton's Method: 10
The square root of 25.0 using Newton's Method after 10 iterations is approximately: 5.000000